﻿using UnityEngine;

namespace Framework
{
    public class UILayer
    {
        protected GameObject _gameObject;
        protected RectTransform _transform; 
        
        public UILayer(string name, Transform root)
        {
            _gameObject = new GameObject(name, typeof(RectTransform));
            _transform = _gameObject.transform as RectTransform;
            _transform.SetParent(root, false);
            _transform.anchorMin = Vector2.zero;
            _transform.anchorMax = Vector2.one;
            _transform.offsetMin = Vector2.zero;
            _transform.offsetMax = Vector2.zero;
        }

        public RectTransform GetTransform()
        {
            return _transform;
        }

        public void AddChild(Transform child, bool worldPositionStays)
        {
            child.SetParent(_transform, worldPositionStays);
            OnChildAdd();
        }

        public void RemoveChild(Transform child)
        {
            child.SetParent(null, false);
            OnChildRemove();
        }

        public void SetAsFirstSibling(Transform child)
        {
            child.SetAsFirstSibling();
            OnChildSetAsFirstSibling();
        }

        public void SetAsLastSibling(Transform child)
        {
            child.SetAsLastSibling();
            OnChildSetAsLastSibling();
        }
        
        public virtual void SetFillWidth(float fillWidth, float width)
        {
            float halfPercent = 0.5f * fillWidth / width;
            Vector2 anchorMin = Global.Vec2;
            anchorMin.x = halfPercent;
            anchorMin.y = 0;
            _transform.anchorMin = anchorMin;
            Vector2 anchorMax = Global.Vec2;
            anchorMax.x = 1f - halfPercent;
            anchorMax.y = 1f;
            _transform.anchorMax = anchorMax;
        }

        public virtual void SetFillHeight(float fillHeight, float height)
        {
            float halfPercent = 0.5f * fillHeight / height;
            Vector2 anchorMin = Global.Vec2;
            anchorMin.x = 0;
            anchorMin.y = halfPercent;
            _transform.anchorMin = anchorMin;
            Vector2 anchorMax = Global.Vec2;
            anchorMax.x = 1f;
            anchorMax.y = 1f - halfPercent;
            _transform.anchorMax = anchorMax;
        }

        protected void OnChildAdd()
        {
            
        }

        protected void OnChildRemove()
        {
            
        }

        protected void OnChildSetAsFirstSibling()
        {
            
        }

        protected void OnChildSetAsLastSibling()
        {
            
        }
    }
}